import router, { constantRoutes } from '@/router'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'

const _import = require('@/router/_import_' + process.env.NODE_ENV)

/**
 * 递归格式化动态路由
 * @param {Array} asyncRouterMap 原始路由数组
 * @returns {Array} 格式化后的路由数组
 */



function filterAsyncRouter(asyncRouterMap) {
  if (!asyncRouterMap || !Array.isArray(asyncRouterMap)) {
    return []
  }

  return asyncRouterMap.filter(route => {
    // 防止死循环，检查路由路径是否有效
    if (!route || !route.path) {
      return false
    }

    // 处理component
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        try {
          // 处理字符串类型的组件路径
          if (typeof route.component === 'string') {
            // 移除开头的views/前缀，因为_import函数会自动添加
            let componentPath = route.component
            if (componentPath.startsWith('views/')) {
              componentPath = componentPath.replace('views/', '')
            }

            // 确保不会重复添加"index"
            if (componentPath.endsWith('/index')) {
              route.component = _import(componentPath)
            } else {
              route.component = _import(componentPath)
            }
          }
        } catch (e) {
          // 尝试使用路径推断组件位置
          try {
            // 移除开头的斜杠，因为_import会自动添加@/views/
            let inferredPath = route.path.replace(/^\//, '')

            // 如果路径是userinfo，直接使用userInfo/index
            if (inferredPath === 'userinfo') {
              inferredPath = 'userInfo/index'
            }
            // 否则使用标准格式
            else {
              inferredPath = `${inferredPath}/index`
            }

            route.component = _import(inferredPath)
          } catch (e2) {
            // 如果组件加载失败，返回一个空组件
            route.component = () => import('@/views/404.vue')
          }
        }
      }
    }

    // 确保meta对象存在
    if (!route.meta) {
      route.meta = {}
    }

    // 确保title存在
    if (!route.meta.title && route.name) {
      route.meta.title = route.name
    }

    // 处理子路由
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    } else {
      // 确保children是数组或null
      route.children = route.children || null
    }

    return true
  })
}

// 检查路由是否已存在于constantRoutes中
function isRouteExist(path) {
  // 检查一级路由
  const existingRoute = constantRoutes.find(route => route.path === path)
  if (existingRoute) {
    return true
  }

  // 检查子路由
  for (const route of constantRoutes) {
    if (route.children) {
      const childRoute = route.children.find(child => route.path + '/' + child.path === path)
      if (childRoute) {
        return true
      }
    }
  }

  return false
}

const state = {
  routes: constantRoutes,
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  // 新增：重置路由状态
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = constantRoutes
  }
}

const actions = {
  generateRoutes({ commit }, asyncRoutes) {
    return new Promise(resolve => {
      let accessedRoutes = []
      if (asyncRoutes && asyncRoutes.length > 0) {
        // 过滤掉已经存在的路由
        const uniqueRoutes = asyncRoutes.filter(route => !isRouteExist(route.path))

        accessedRoutes = filterAsyncRouter(uniqueRoutes)
      }

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },

  // 新增：重置路由
  resetRoutes({ commit }) {
    commit('RESET_ROUTES')
    return Promise.resolve()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 